package com.thunbu.thunbu_meeting_system

import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.cathu.lib_commonkt.base.BaseMVVMActivity
import com.hjq.toast.ToastUtils
import com.honeywell.rfidservice.RfidManager
import com.honeywell.rfidservice.rfid.RfidReader
import com.thunbu.thunbu_meeting_system.activity.*
import com.thunbu.thunbu_meeting_system.bean.HomeModel
import com.thunbu.thunbu_meeting_system.bean.HomePageTypeVO
import com.thunbu.thunbu_meeting_system.databinding.ActivityMainBinding
import com.thunbu.thunbu_meeting_system.databinding.ItemHomeAssetsBinding
import com.thunbu.thunbu_meeting_system.listener.EventSimpleListener
import com.thunbu.thunbu_meeting_system.rfid.WorkMode
import com.thunbu.thunbu_meeting_system.utils.AppUtils
import com.thunbu.thunbu_meeting_system.view.ViewData
import com.thunbu.thunbu_meeting_system.viewMdel.MainViewModel
import java.util.*

/**
 * @Description: 首页
 * @author: Yang.Yang33
 * @Date: 2023/3/20 20:43
 */
class MainActivity : BaseMVVMActivity<ActivityMainBinding, MainViewModel>(), EventSimpleListener {
    private var viewDataList: MutableList<ViewData> = ArrayList()
    private lateinit var mAdapter: BaseVBQuickAdapter<ViewData, ItemHomeAssetsBinding>
    private var haveResumed = false //页面可否显示过


    private val mHandler = Handler(Looper.getMainLooper())


    override fun onMVVMCreated() {
        //todo 缺少icon 缺少都为0情况下圆环显示
        initRv()
        initView()
        initVM()
        initMgr()
        vm.requestData(false)
    }

    private fun initVM() {
        vm.homeInfo.observe(this){
            val spannableString = SpannableString("${it.incompleteTask}/${it.taskCount}")
            spannableString.setSpan(
                StyleSpan(android.graphics.Typeface.BOLD),
                0,
                it.incompleteTask.toString().length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                AbsoluteSizeSpan(20, true),
                0,
                it.incompleteTask.toString().length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                ForegroundColorSpan(Color.parseColor("#222222")),
                0,
                it.incompleteTask.toString().length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            bindViews.tvPdTaskCount.text = spannableString
            bindViews.tvMyAssetsCount.text = it.assetCount.toString()
            bindViews.tvTodoCount.text = it.incompleteTask.toString()
            setRingView(it.homePageTypeVOList)
        }
    }

    private fun initMgr() {
        RfidManager.create(this, RfidManager.CreatedCallback { rfidManager ->
            App.instance.rfidMgr = rfidManager
            App.instance.rfidMgr?.addEventListener(this)
            App.instance.rfidMgr?.setDevicePower(true)
            mHandler.post {
                if(App.instance.rfidMgr?.connect(null)?:false){
                    Log.e("fancl","rfid 扫描仪连接失败")
                }
            }

        })
    }

    private fun initView() {
        bindViews.ivToolbarSet.setOnClickListener {
            gotoActivity<SettingActivity>()
        }
        bindViews.rlPdTask.setOnClickListener {
            gotoActivity<InventoryTaskListActivity>()
        }
        bindViews.rlMyAssets.setOnClickListener {
            gotoActivity<MyAssetsActivity>()
        }
        bindViews.rlTodo.setOnClickListener {
            gotoActivity<TodoActiviy>()
        }

    }

    val color = mutableListOf("E44F76","FE9235","3FCB7A","5688EB")
    val icon = mutableListOf(R.mipmap.icon_home_item1,R.mipmap.icon_home_item2,R.mipmap.icon_home_item4,R.mipmap.icon_home_item4)

    private fun setRingView(homePageTypeVOList: List<HomePageTypeVO>?) {
        viewDataList.clear()
        var count = 0
        if(!homePageTypeVOList.isNullOrEmpty()){
            homePageTypeVOList.forEachIndexed{index, homePageTypeVO ->
                var mColor = color[index%color.size]
                var mIcon = icon[index%icon.size]
                viewDataList.add(
                        ViewData(
                                homePageTypeVO.assetName,
                                homePageTypeVO.count,
                                Color.parseColor("#${mColor}"),
                                Color.parseColor("#26${mColor}"),
                                mIcon
                        )
                )
            }
            mAdapter.setNewData(viewDataList)
        }

        viewDataList.forEach {
            count += it.value
        }
        //都为0,不知道显示啥,先显示个灰的圈把
        if (count == 0) {
            viewDataList.clear()
            viewDataList.add(
                ViewData(
                    "",
                    1,
                    Color.parseColor("#999999"),
                    Color.parseColor("#26999999"),
                    0
                )
            )
        }
        bindViews.ringChart.setNoData(count == 0)
        bindViews.ringChart.setData(viewDataList)
    }

    private fun initRv() {
        bindViews.rv.layoutManager = LinearLayoutManager(this)
        mAdapter = bindViews.rv.bindAdapter { item, position ->
            ivIcon.setImageResource(item.icon)
            tvName.text = item.text
            tvCount.text = item.value.toString()
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
//            ToastUtils.show("hahaha${position}")
            gotoActivity<MyAssetsActivity>{
                putExtra(MyAssetsActivity.TYPE_NAME,mAdapter.data[position].text)
            }
        }
    }


    override fun onDeviceConnected(p0: Any?) {
        super.onDeviceConnected(p0)
        Log.i("fancl","onDeviceConnected 连接成功")
        App.instance.rfidMgr?.createReader()
    }

    override fun onDeviceDisconnected(p0: Any?) {
        Log.i("fancl","onDeviceDisconnected 连接失败")
        App.instance.mRfidReader = null
    }

    override fun onReaderCreated(p0: Boolean, rfidReader: RfidReader) {
        App.instance.mRfidReader = rfidReader
        WorkMode.getInstance(rfidReader.isHonReader)
                .enableMode(WorkMode.Modes.MODE_ANTI_INTERFERENCE.value(),rfidReader)
    }

    override fun onResume() {
        super.onResume()
        if(!haveResumed){
            haveResumed = true
        }else{
            vm.requestData(true)
        }
        App.instance.rfidMgr?.addEventListener(this)
    }

    override fun onPause() {
        super.onPause()
        mHandler.removeCallbacksAndMessages(null)
        App.instance.rfidMgr?.removeEventListener(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        App.instance.disconnect()
    }


}